//
//  PicDisplayViewController.m
//  RoadLine
//
//  Created by dllo on 15/4/23.
//  Copyright (c) 2015年 RedFireNoodles. All rights reserved.
//

#import "PicDisplayViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "PlaceModel.h"
#import "PicDisplayCell.h"
#import "MJRefresh.h"
#import "ImgViewController.h"

// 定义宏
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height



@interface PicDisplayViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

// 装数据的数组
@property(nonatomic, retain)NSMutableArray *picArr;
// 图片显示视图
@property(nonatomic, retain)UICollectionView *collectionView;
// 刷新数据时，网址解析用的页数
@property(nonatomic, assign)NSInteger page;

@property(nonatomic, retain)UIActivityIndicatorView *activity;

@end

@implementation PicDisplayViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.picArr = [NSMutableArray array];
 
        self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    
    return self;
}

// 数据解析
-(void)data{
    // 多线程
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        
        NSInteger number = self.page * 21;
        NSString *path = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/photos/?start=%ld&count=21&gallery_mode=true", self.type, self.pic_id, number];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSMutableDictionary *dic = responseObject;
            NSMutableArray *arr = [dic objectForKey:@"items"];
            for (NSMutableDictionary *dic in arr) {
                PlaceModel *place = [[PlaceModel alloc] init];
                [place setValuesForKeysWithDictionary:dic];
                [self.picArr addObject:place];
                [place release];
                
            }
            
//            [self.activity stopAnimating];
            [self.collectionView reloadData];
            [self.collectionView.footer endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
           
        }];
        self.page++;
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSString *str = [NSString stringWithFormat:@"%@图片精选",self.name];
    self.title = str;
    
    // 改变navigationBar上字体颜色
    UILabel *titleLabelPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabelPrice.font = [UIFont boldSystemFontOfSize:18];
    titleLabelPrice.textColor = [UIColor whiteColor];
    titleLabelPrice.backgroundColor = [UIColor clearColor];
    titleLabelPrice.text = self.title;
    self.navigationItem.titleView = titleLabelPrice;
    [titleLabelPrice release];
    
   
    self.view.backgroundColor = [UIColor whiteColor];
    
    // collectionView 瀑布流设置
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH/3 - 25, WIDTH/3 - 25);
    flowLayout.minimumInteritemSpacing = WIDTH/30 - 10;
    flowLayout.minimumLineSpacing = WIDTH/30;
    flowLayout.sectionInset = UIEdgeInsetsMake(WIDTH/30, WIDTH/15, 30, WIDTH/15);
    // collectionView 设置
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[PicDisplayCell class] forCellWithReuseIdentifier:@"reuse"];
    self.collectionView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    
    self.page = 0;
    [self.collectionView addLegendFooterWithRefreshingBlock:^{
        [self data];
        [self.collectionView reloadData];

    }];
    [self.collectionView.footer beginRefreshing];
    
    [flowLayout release];
    [_collectionView release];
//    [self.collectionView addSubview:self.activity];
//    self.activity.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
//    [self.activity startAnimating];
    [_activity release];
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
}

// collectionView 必须实现方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.picArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    PicDisplayCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
//    PlaceModel *place = [[PlaceModel alloc] init];
    PlaceModel *place = self.picArr[indexPath.row];
    NSURL *url = [NSURL URLWithString:place.photo_w640];
    [cell.myImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
//    [place release];
    return cell;
        
}

// 设置白天模式
- (void)setLightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    self.collectionView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
}

// 设置夜间模式
- (void)setNightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
    self.collectionView.backgroundColor = [UIColor blackColor];
}

// 跳转到相册页面
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ImgViewController *imageVC = [[ImgViewController alloc] init];
    imageVC.index = indexPath.row;
    imageVC.type = self.type;
    imageVC.pic_id = self.pic_id;
    [self.navigationController pushViewController:imageVC animated:YES];
    
    [imageVC release];
}

-(void)dealloc{
    

    [_picArr release];
    [_collectionView release];
    [_activity release];

    [super dealloc];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
